package com.atwulidun.search;

import java.util.ArrayList;

public class InsertValueSearch {
    public static void main(String[] args) {
        int[] arr = new int[100];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = i + 1;
        }
        arr[97] = 100;
        arr[98] = 100;
        ArrayList<Integer> list = insertValueSearch(arr, 0, arr.length - 1, 100);
        System.out.println(list);
    }

    public static ArrayList<Integer> insertValueSearch(int[] arr, int left, int right, int findVal) {
        // 特别注意：递归结束的条件一定要有findVal < arr[left] || findVal > arr[right]
        // 因为mid的计算要有findVal参与，若其值很大，那么mid是有可能越界的！！！！！！！！
        // 所以加入这两个判断既可以优化代码，也可以防止mid越界
        if (left > right || findVal < arr[left] || findVal > arr[right]) {
            return new ArrayList<>();
        }
        int mid = left + (findVal - arr[left]) / (arr[right] - arr[left]) * (right - left);
        int midVal = arr[mid];
        if (findVal < midVal) {
            return insertValueSearch(arr, left, mid - 1, findVal);
        } else if (findVal > midVal) {
            return insertValueSearch(arr, mid + 1, right, findVal);
        } else {
            ArrayList<Integer> list = new ArrayList<>();
            int leftIndex = mid - 1;
            while (leftIndex >= 0 && arr[leftIndex] == findVal) {
                list.add(leftIndex);
                leftIndex--;
            }
            list.add(mid);
            int rightIndex = mid + 1;
            while (rightIndex <= arr.length - 1 && arr[rightIndex] == findVal) {
                list.add(rightIndex);
                rightIndex++;
            }
            return list;
        }
    }
}
